package com.ddwl.gate.domain.gaode.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.gate.domain.gaode.api.GaoDeApi;
import com.ddwl.gate.domain.gaode.api.vo.PoiResp;
import com.ddwl.gate.domain.gaode.api.vo.PoiVo;
import com.ddwl.gate.domain.gaode.dao.GaoDePoiDao;
import com.ddwl.gate.domain.gaode.dao.model.GaoDePoi;
import com.ddwl.gate.domain.gaode.vo.QueryGaoDePoiVo;
import com.ddwl.gate.service.RegionService;
import com.ddwl.schema.vo.gate.RegionVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GaoDeService {

    @Resource
    private GaoDeApi gaoDeApi;
    @Resource
    private GaoDePoiDao gaoDePoiDao;
    @Resource
    private RegionService regionService;

    @Value("${amap.key}")
    private String key;

    private Integer pageSiz = 25;


    public List<PoiVo> queryPoi(QueryGaoDePoiVo queryGaoDePoiVo){
        Map<String, Object> map = BeanConverUtils.beanToMap(queryGaoDePoiVo);
        map.put("key",key);
        map.put("page_size",pageSiz.toString());
        map.put("show_fields","business,photos");
        PoiResp poiResp = null;
        if(StrUtil.isNotBlank(queryGaoDePoiVo.getLocation())){
            poiResp = gaoDeApi.queryAroundPoi(map);
        }else {
            if(StrUtil.isBlank(queryGaoDePoiVo.getRegion())){
                map.put("region","hangzhou");
            }
            poiResp = gaoDeApi.queryPoi(map);
        }
        if(poiResp!=null&&"OK".equals(poiResp.getInfo())){
            filterAndSavePois(poiResp);
            return poiResp.getPois();
        }else {
            log.error("map={},resp={}", JSON.toJSONString(map),JSON.toJSONString(poiResp));
            throw new RuntimeException("调用高德异常:");
        }
    }

    public void place(String cityName) {
        //RegionVo regionVo=regionService.getRegionById(cityName);
        //log.info("regionVos : {}", JSON.toJSONString(regionVo));
        //060500,060501,060502,060703,060705,060706,060800,060900,061000,061001,
        //String types = "061100,061101,061102,061207";
        String types = "童装|童鞋|服装|母婴";
        //if (null!=regionVo) {
//            for (RegionVo vo : regionVos) {
                //for(String type: types.split(",")){
                    importPoi(types,cityName,1);
                //}
//            }
        //}
    }

    public void importPoi(String types,String region ,Integer pageNum){
        Map<String, Object> map = new HashMap<>();
        map.put("key",key);
        //map.put("types",types);
        map.put("keywords", types);
        map.put("region",region);
//        map.put("city_limit","true");
        map.put("show_fields","business,photos");
        map.put("page_size",pageSiz.toString());
        map.put("page_num",pageNum.toString());
        PoiResp poiResp = gaoDeApi.queryPoi(map);
        if (poiResp != null && "OK".equals(poiResp.getInfo())) {
            filterAndSavePois(poiResp);
            if (poiResp.getCount() >= pageSiz) {
                importPoi(types, region, pageNum + 1);
            }
        } else {
            log.error("types={},region={},pageNum={} errmsg={}", types, region, pageNum, poiResp.getInfo());
            throw new RuntimeException("爬取数据异常，退出爬虫");
        }

    }

    private void filterAndSavePois(PoiResp poiResp) {
        if (poiResp.getPois() != null && poiResp.getPois().size() > 0) {
            List<GaoDePoi> gaoDePoiList = conversionPoi(poiResp.getPois());
            if (!CollectionUtils.isEmpty(gaoDePoiList)) {
                List<GaoDePoi> gaoDePois = gaoDePoiDao.selectByPrimaryKeys(gaoDePoiList.stream().map(GaoDePoi::getId).collect(Collectors.toList()));
                for (GaoDePoi gaoDePoi : gaoDePois) {
                    for (GaoDePoi addGaoDePoi : gaoDePoiList) {
                        if (gaoDePoi.getId().equals(addGaoDePoi.getId())) {
                            gaoDePoiList.remove(addGaoDePoi);
                            break;
                        }
                    }
                }
                if (CollUtil.isNotEmpty(gaoDePoiList)) {
                    gaoDePoiDao.insertList(gaoDePoiList);
                }
            }
        }
    }


    public List<GaoDePoi> conversionPoi(List<PoiVo> pois){
        List<GaoDePoi> gaoDePoiList = new ArrayList<>();
        for(PoiVo poiVo : pois){
            GaoDePoi gaoDePoiexit = gaoDePoiList.stream().filter(g->g.getId().equals(poiVo.getId())).findFirst().orElse(null);
            if(gaoDePoiexit!=null){
                continue;
            }
            GaoDePoi gaoDePoi =   BeanConverUtils.convertBean(poiVo,GaoDePoi.class );
            JSONObject business =  JSONObject.parseObject(poiVo.getBusiness());
            if (business == null || !StringUtils.hasText(business.getString("tel"))) {
                continue;
            }
            String[] locations = poiVo.getLocation().split(",");
            if(locations!=null&&locations.length>1){
                gaoDePoi.setLon(Double.valueOf(poiVo.getLocation().split(",")[0]));
                gaoDePoi.setLat(Double.valueOf(poiVo.getLocation().split(",")[1]));
            }
            if(business!=null){
                String tel = "";
                String telStr = business.getString("tel");
                if (telStr.contains(";")) {
                    String[] arr = telStr.split(";");
                    for (String str : arr) {
                        if (str.startsWith("1")) {
                            tel = str;
                            break;
                        }
                    }
                }else{
                    if (telStr.startsWith("1")) {
                        tel = telStr;
                    }
                }
                if (!StringUtils.hasText(tel)) {
                    continue;
                }
                gaoDePoi.setBusinessArea(business.getString("business_area"));
                gaoDePoi.setTel(tel);
                gaoDePoi.setRectag(business.getString("rectag"));
                gaoDePoi.setRating(business.getString("rating"));
            }
            gaoDePoiList.add(gaoDePoi);
        }
        return gaoDePoiList;
    }

}
